undefined method `code' for nil:NilClass message with rails and a legacy database

Posted by Jude Osborn on Stack Overflow See other posts from Stack Overflow or by Jude Osborn
Published on 2011-01-17T22:48:50Z Indexed on 2011/01/17 22:53 UTC
Read the original article Hit count: 124

Filed under:
|

I'm setting up a very simple rails 3 application to view data in a legacy MySQL database. The legacy database is mostly rails ORM compatible, except that foreign key fields are pluralized. For example, my "orders" table has a foreign key field to the "companies" table called "companies_id" (rather than "company_id"). So naturally I'm having to use the ":foreign_key" attribute of "belongs_to" to set the field name manually.

I haven't used rails in a few years, but I'm pretty sure I'm doing everything right, yet I get the following error when trying to access "order.currency.code":

undefined method `code' for nil:NilClass

This is a very simple application so far. The only thing I've done is generate the application and a bunch of scaffolds for each of the legacy database tables. Then I've gone into some of the models to make adjustments to accommodate the above mentioned difference in database naming conventions, and added some fields to the views. That's it. No funny business.

So my database tables look like this (relevant fields only):

orders
------
id
description
invoice_number
currencies_id

currencies
----------
id
code
description

My Order model looks like this:

class Order < ActiveRecord::Base
  belongs_to :currency, :foreign_key=>'currencies_id'
end

My Currency model looks like this:

class Currency < ActiveRecord::Base
    has_many :orders
end

The relevant view snippet looks like this:

<% @orders.each do |order| %>
  <tr>
    <td><%= order.description %></td>
    <td><%= order.invoice_number %></td>
    <td><%= order.currency.code %></td>
  </tr>
<% end %>

I'm completely out of ideas. Any suggestions?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about ruby-on-rails